import { asyncRoutes, constantRoutes } from '@/router'
import { getPermissionMenu } from '@/utils/auth'
import Layout from '@/layout';
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}



const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      var listPermissionRouter = getPermissionMenu()
      //debugger
      let accessedRoutes=[]
      if(listPermissionRouter){
        var tree = _listToTree(listPermissionRouter.filter(s=>s.type==1))
        var apiRouter = _filterAsyncRouter(tree)
        accessedRoutes = apiRouter || []
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

function _filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串，转换为组件对象
  const dynamicRouteString = asyncRouterMap.filter(route => {
    if (route.component&&typeof route.component == 'string') {
      if (route.component.toLowerCase() == 'layout') {//Layout组件特殊处理
        route.component = Layout
      } else {
        try {
          route.component = require(`@/views/${route.component}`).default //动态获取组件
        } catch (error) {
          console.error("路由error", error)
        }
      }
    }
    if (route.children && route.children.length) {
      route.children = _filterAsyncRouter(route.children)
    }
    return true
  })
  return dynamicRouteString
}



const _listToTree = (list) => {
  let result = list.reduce((prev, item) => {
    prev[item.parentId] ? prev[item.parentId].push(item) : (prev[item.parentId] = [item])
    return prev
  }, {})
  for (let prop in result) {
    result[prop].forEach((item, i) => {
      result[item.id] ? (item.children = result[item.id]) : ''
    })
  }
  return result[0]
}
// const filterPermissionRouter=(routers)=>{
//   var listPermissionRouter=getPermissionMenu()
//   routers.forEach(e => {
//     if(!listPermissionRouter.some(s=>s.name==e.name)){
//       delete e

//     }
//   });
//   return 
// }


export default {
  namespaced: true,
  state,
  mutations,
  actions
}
